from django.conf import settings
import hashlib
import requests
from xml.etree import ElementTree as et
import time

# 生成32位的随机字符串
def get_nonce_str():
    import uuid

    return str(uuid.uuid4()).replace('-', '')

class WeChatRefundPay(object):
    def __init__(self, order_id, refund_id, total_fee, refund_fee, nonce_str):
        """
        :param order_id: 商户订单编号，32字符以内
        :param refund_id: 商户退款订单号
        :param total_fee: 订单金额，单位为分
        :param refund_fee: 退款金额，单位为分
        :param nonce_str: 32位随机字符串
        :param openid: 用户的openid(唯一标识)
        appid '微信appid'
        appid = settings.WECHAT_APP_ID
        AppSecret '微信AppSecret'
        AppSecret = settings.WECHAT_APP_KEY
        mcg_id '微信商户id'
        mch_id = settings.WECHAT_PAY_ID
        api_key '微信支付密钥'
        api_key = settings.WECHAT_PAY_API_KEY
        """
        self.api_key = settings.WECHAT_PAY_API_KEY
        self.params = {
            'appid': settings.WECHAT_APP_ID,
            'mch_id': settings.WECHAT_PAY_ID,
            'nonce_str': nonce_str,
            'out_trade_no': order_id,
            'out_refund_no': refund_id,
            'total_fee': total_fee,
            'refund_fee': refund_fee,
        }
        self.WxPay_refund_request_url = 'https://api.mch.weixin.qq.com/secapi/pay/refund'  # 小程序发起退款支付链接
        self.error = None

    def key_value_url(self, value):
        # 将键值对转换成key1=value1&key2=value2
        string_sign = ''
        for k in sorted(value.keys()):  # sorted : ASCII字典序排序
            string_sign += "{0}={1}&".format(k, value[k])
        return string_sign

    def get_sign(self, params):
        """
        生成sign签名
        :param params: 传入参数
        :return:
        """
        stringA = self.key_value_url(params)
        stringSignTemp = stringA + 'key=' + self.api_key  # APIKEY,API密钥，需要在商户后台设置
        sign = hashlib.md5(stringSignTemp.encode('utf-8')).hexdigest().upper()
        params['sign'] = sign

    def get_req_xml(self):
        """
        拼接xml
        :return:
        """
        self.get_sign(self.params)
        xml = "<xml>"
        for k in sorted(self.params.keys()):
            xml += '<{0}>{1}</{0}>'.format(k, self.params[k])
        xml += "</xml>"
        return xml.encode('utf-8')

    def get_result(self):
        """
        发起请求
        :return:
        """
        # 配置证书位置
        cert_path = "{}/apps/orders/keys/apiclient_cert.pem".format(settings.BASE_DIR)
        key_path  = "{}/apps/orders/keys/apiclient_key.pem".format(settings.BASE_DIR)
        xml = self.get_req_xml()
        refundXML = requests.post(self.WxPay_refund_request_url, cert=(cert_path, key_path),
                                  data=xml)
        refundXML.encoding = 'utf-8'
        refundXML = refundXML.text
        root = et.fromstring(refundXML)
        if root.find("result_code").text == 'SUCCESS':
            data = {
                'Resultcode':1,
                'message': "退款成功"
            }
            return data
        else:
            self.error = root.find("return_msg").text
            print(self.error)
            data = {
                'Resultcode': 0,
                'message': "支付失败",
                'error': self.error
            }
            return data
